package com.chinaunicom.emergency.service;

import com.chinaunicom.emergency.constant.ConstantUtil;
import com.chinaunicom.emergency.model.YjglOrg;
import com.chinaunicom.emergency.util.JPAUtil;
import com.chinaunicom.emergency.repository.OrgRepository;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author liliang
 * @Date 2019/12/17 15:37
 * @Version 1.0
 */
@Service
@Log4j2
public class OrgService {
    @Autowired
    private OrgRepository orgRepository;
    @Autowired
    RedisService redisService;


    public void updateRedis(Boolean updateNow){
        if(updateNow){
            updateRedisOrg();
        }else{
            updateRedisByAsync();
        }
    }


    @Async
    public void updateRedisByAsync(){
        updateRedisOrg();
    }

    public void updateRedisOrg(){
        Map<String, YjglOrg> map = new HashMap<String, YjglOrg>();
        map = getAllNameStrByParentId("0",map);
        if(null != map){
            Map mapOrgIdStr = new HashMap<String,String>();
            for(Map.Entry<String, YjglOrg> entry : map.entrySet()){
                if(StringUtils.isNotBlank(entry.getKey()) && null != entry.getValue()){
                    mapOrgIdStr.put(entry.getValue().getOrgId(),entry.getValue().getOrgNameStr());
                }
            }
            if(null != mapOrgIdStr){
                redisService.deleteKey(ConstantUtil.PREFIX_ORG_TREE+":ORGID_NAMESTR");
                redisService.putHash(ConstantUtil.PREFIX_ORG_TREE+":ORGID_NAMESTR",mapOrgIdStr);
            }
        }
    }

    /**
     * 获取所有的组织机构拼接数据,map中key为pid,value为YjglOrg对象,其中YjglOrg中的orgNameStr为组织机构全名
     * @param parentId
     * @param map
     * @return
     */
    private Map<String, YjglOrg> getAllNameStrByParentId(String parentId, Map<String, YjglOrg> map) {
        List<YjglOrg> oAuthOrgsList = orgRepository.findByParentIdAndIsSoftDel(parentId,0);
        if(!CollectionUtils.isEmpty(oAuthOrgsList)){
            for(YjglOrg org : oAuthOrgsList){
                if(null != org){
                    if(StringUtils.isNotBlank(parentId)){
                        YjglOrg orgStrRedis = map.get(org.getParentId());
                        if(null != orgStrRedis && !StringUtils.isBlank(orgStrRedis.getOrgNameStr())){
                            org.setOrgNameStr(orgStrRedis.getOrgNameStr()+"-"+org.getOrgName());
                        }else{
                            org.setOrgNameStr(org.getOrgName());
                        }
                    }else{
                        org.setOrgNameStr(org.getOrgName());
                    }
                    map.put(org.getPid(),org);
                    getAllNameStrByParentId(org.getPid(),map);
                }
            }
        }
        return map;
    }


    public Specification findPageByCondition(Map para){
        return new Specification<YjglOrg>() {

            @Override
            public Predicate toPredicate(Root<YjglOrg> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();

                JPAUtil.like(list,cb,root,"orgName",para);
                JPAUtil.equal(list,cb,root,"isSoftDel",para);
                if(para.containsKey("parentId")){
                    JPAUtil.equal(list,cb,root,"parentId",para);
                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }
}
